#include "CtrlDataTest.h"
#include "CAppCtx.h"
#include "CRadarTest.h"
#include "GenOpt.h"
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QIcon>
#include <QStandardItemModel>
#include <QTextStream>
#include <QThread>
#include <qtmetamacros.h>

CtrlDataTest::CtrlDataTest(QWidget *parent) {
  ui.setupUi(this);
  OnInitWindow();
}

CtrlDataTest::~CtrlDataTest() {
  if (thread_test_) {
    thread_test_->quit();
    thread_test_->wait();
    delete thread_test_;
  }
}

void CtrlDataTest::AddMsg(QString msg) {
  QListWidgetItem *item = new QListWidgetItem(msg, ui.listWidgetMsg);
  ui.listWidgetMsg->addItem(item);
  ui.listWidgetMsg->setCurrentRow(ui.listWidgetMsg->count() - 1);
}

void CtrlDataTest::OnInitWindow() {
  setWindowTitle("雷达数据测试");
  setWindowIcon(QIcon(":/ICON/test.png"));
  ui.pbStop->setEnabled(false);
  ui.processBarConv->setVisible(false);
  thread_test_ = new CThreadRadarTest(this);
  QObject::connect(thread_test_, &CThreadRadarTest::setText, this,
                   &CtrlDataTest::AddMsg);
  QObject::connect(thread_test_, &CThreadRadarTest::finished, this,
                   &CtrlDataTest::SetProcess);
}

void CtrlDataTest::on_pbInputBrowse_clicked() {
  QString file_path = QFileDialog::getExistingDirectory(
      this, "选择视频文件路径", "C:/", QFileDialog::DontResolveSymlinks);
  ui.leInputFolder->setText(file_path);
  folder_input_ = file_path;
  AddMsg(QString("输入文件夹配置为%1").arg(folder_input_));
  file_list_.clear();
  CGenOpt::SearchAllFileInPath(file_path, file_list_);
  if (file_list_.count() == 0) {
    AddMsg(QString("输入路径中未找到任何视频文件"));
    return;
  }
  AddMsg(QString("输入路径中找到%1个视频文件").arg(file_list_.count()));
  ui.listWidgetFile->clear();
  ui.listWidgetFile->addItems(file_list_);
}

int CtrlDataTest::SetProcess(int proc) {
  ui.processBarConv->setValue(proc);
  if (proc == 100) {
    ui.pbInputBrowse->setEnabled(true);
    ui.pbStart->setEnabled(true);
    ui.pbStop->setEnabled(false);
    ui.processBarConv->setVisible(false);
    AddMsg(QString("测试完成!"));
  }
  return 0;
}

int CtrlDataTest::Start() {
  thread_test_->SetOutputFolder(folder_input_);
  thread_test_->SetFileList(file_list_);
  thread_test_->SetStop(false);
  thread_test_->start();
  return 0;
}

void CtrlDataTest::on_pbStart_clicked() {
  if (folder_input_.size() == 0) {
    AddMsg(QString("没有选择输入文件夹!"));
    return;
  }
  if (file_list_.size() == 0) {
    AddMsg(QString("路径中没有视频文件!"));
    return;
  }
  ui.pbInputBrowse->setEnabled(false);
  ui.pbStart->setEnabled(false);
  ui.pbStop->setEnabled(true);
  ui.processBarConv->setVisible(true);
  ui.processBarConv->setRange(0, 100);
  ui.processBarConv->setValue(0);
  Start();
}
void CtrlDataTest::on_pbStop_clicked() {
  AddMsg(QString("正在停止..."));
  thread_test_->SetStop(true);
  thread_test_->quit();
  thread_test_->wait();
}
